<?php
	require_once('../inc/fnc.php');

	// Initializing variables
	$username = $_POST['name'];
	$email = mysql_prep($_POST['email']);
	$pwd = sha1($_POST['pwd']);
	$time = time();

	//Check is pwd is null or not
	$error['pwd'] = ($pwd == '' || $pwd == NULL || $pwd == "Password") ? $error['pwd']= 'null' : $error['pwd']= 'clear';

	//Check username validity & availability
	if (!preg_match('/^[a-zA-Z0-9_\.-]{5,20}$/', $username)) { $error['name']= 'false'; } elseif (!checkavailable($username)) { $error['name']= 'exist'; } else { $error['name']= 'clear'; }

	//check email validity and availability
	if (!check_email_address($email)) {
		$error['reg']= 'invalid';
	} else {
		$error['reg'] = (isEmailAvailable($email)) ? 'clear' : 'true';	//If true, email not available; if false, email is available
	}
	
	$query = mysql_query("select max(userid) as uid from users");
	while($row = mysql_fetch_array($query)) {
		$userId = $row['uid'];
		$userId++;
	}

	//if everything is clear go ahead and sign up
	if($error['reg'] == 'clear' && $error['pwd'] == 'clear' && $error['name'] == 'clear') {
		// Inserting basic user data into 'users' database table 
		 $query = "INSERT INTO `users` (`userid`, `username`, `pwd`, `email`, `profile image path`, `time`, `delete flag`, `Isadmin`, `email varification`) 
					VALUES ('{$userId}', '{$username}', '{$pwd}', '{$email}', 'users/defaultAvatar/', '{$time}', 'N', 'N', 'N')";

		$result = mysql_query( $query, $connection) or die("Failed To Register User: " . mysql_error());

		//Getting the id (which is going to be the user Id) number of the last inserted row
		$userId = mysql_insert_id();

		// Generating activation link
		$rand = genRandomString(10);
		//$actLnk = DOMAIN . "?id=" . $userId . "&key=" . $rand . "&email=" . $email;
		$actLnk = DOMAIN . "/activate/" . $userId . "/" . $rand;
		
		// Storing activation info in db
		$query = "INSERT INTO `activate` (`rand`, `email`, `flag`) 
					VALUES ('{$rand}', '{$email}', '0')";
					  
		$result = mysql_query( $query, $connection) or die("Inserting Activation link info Failed: " . mysql_error());

		// Sending Activation link to user
		// subject
		$subject = 'Activation link to your Next Twist story account';
		
		// message
		$message = "<html>
					<head>
					  <title>Come on Board and start writing your own stories!!</title>
					</head>
					<body>
					  <p>Click on the link below to activate your Next Twist account</p>
					  <table>
						<tr>
						  <a href='{$actLnk}'>Activate now</a>
						</tr>
					  </table>
					</body>
					</html>";

		// Mail it
		$error['success'] = (sendMail($email, $subject, $message)) ? 'true' : 'false';
	}

	echo json_encode($error);

?>